package com.example.widget_lib.widget.legend;

import com.example.widget_lib.ResourceTable;
import com.example.widget_lib.utils.AttrUtils;
import com.example.widget_lib.utils.LogUtil;
import com.example.widget_lib.utils.PxUtil;
import com.example.widget_lib.widget.PointView;
import ohos.aafwk.ability.AbilityForm;
import ohos.aafwk.ability.OnClickListener;
import ohos.aafwk.ability.ViewsStatus;
import ohos.agp.components.*;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.global.resource.solidxml.TypedAttribute;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 图例控件
 *
 * @autor hongbing
 * @date 2019/3/28
 */
public class LegendView extends DirectionalLayout {

    private Context mContext;
    // 图例的列宽
    private int mColumnWidth;
    // 图例行间距
    private int mLegendVerMargin;
    // 图例字体颜色
    private int mLabelColor;
    // 图例字体大小
    private float mLabelSize;
    // 图例文案和圆点的间距
    private int mLegendLabelAndPointMargin;
    // 图例每行第一个左侧偏移量
    private int mLegendOffsetLeft;
    // 动态计算出来的列数
    private int mColumn;
    private int width;
    private int margin;
    private int pointWH = 50;

    public LegendView(Context context) {
        this(context, null);
    }

    public LegendView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initView(context, attrSet);

    }

    private void initView(Context context, AttrSet attrs) {
        mContext = context;
        setOrientation(DirectionalLayout.VERTICAL);
//        setGravity(Gravity.CENTER);
        setForegroundGravity(LayoutAlignment.CENTER);
        initAttr(attrs);

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                /**
                 * 动态计算列数
                 */
                width = getWidth();
                int mPadding = getPaddingLeft() + getPaddingRight();
                mColumn = (width - mPadding) / (mColumnWidth + pointWH);
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });
    }


    public LegendView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    @Override
    public void addDrawTask(DrawTask task) {
        super.addDrawTask(task);
        task.onDraw(this, mCanvasForTaskOverContent);
    }

    //    @Override
//    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        super.onLayout(changed, left, top, right, bottom);
//        LogUtil.logD("201812201056",
//                "onLayout->MeasuredWidth = " + getMeasuredWidth() + "->changed = " + changed);
//
//    }

    private void initAttr(AttrSet attrs) {

        mColumnWidth = AttrUtils.getDimensionFromAttr(attrs, "legendView_lv_legend_columnW", (int) PxUtil.vp2px(42));
        mLegendVerMargin = AttrUtils.getDimensionFromAttr(attrs, "legendView_lv_legend_vertical_margin", (int) PxUtil.vp2px(8));
        mLabelColor = AttrUtils.getColorFromAttr(attrs, "legendView_lv_legend_font_color", Color.getIntColor("#2A2A2A"));
        mLabelSize = AttrUtils.getDimensionFromAttr(attrs, "legendView_lv_legend_font_size", (int) PxUtil.fp2px(12));
        mLegendLabelAndPointMargin = AttrUtils.getDimensionFromAttr(attrs, "legendView_lv_legend_labelAndPoint_margin", (int) PxUtil.vp2px(4));
        mLegendOffsetLeft = AttrUtils.getDimensionFromAttr(attrs, "legendView_lv_legend_offset_left", 0);
    }

//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        LogUtil.logD("20190328", "onMeasure = " + getMeasuredWidth());
//    }
//
//    @Override
//    protected void onFinishInflate() {
//        super.onFinishInflate();
//        LogUtil.logD("20190328", "onFinishInflate = " + getMeasuredWidth());
//    }

//    @Override
//    protected void onAttachedToWindow() {
//        super.onAttachedToWindow();
//        LogUtil.logD("20190328", "onAttachedToWindow = " + getMeasuredWidth());
//    }
//
//    @Override
//    protected void onDetachedFromWindow() {
//        super.onDetachedFromWindow();
//        LogUtil.logD("20190328", "onDetachedFromWindow = " + getMeasuredWidth());
//    }

//    @Override
//    public boolean onDrag(Component component, DragEvent event) {
//        width = getWidth();
//        margin = getMarginLeft() + getMarginRight();
//        mColumn = (width - margin) / mColumnWidth;
//        return super.onDrag(component, event);
//
//    }

    /**
     * 没有图例内容
     */
    public void setEmpty() {
        setVisibility(Component.INVISIBLE);
    }

    /**
     * 设置图例数据
     *
     * @param legends
     * @param colors
     */
    public void setData(final List<String> legends, final int[] colors) {
        if (legends == null || legends.isEmpty()) {
            setVisibility(Component.HIDE);
            return;
        }
        if (getVisibility() == Component.HIDE) {
            setVisibility(Component.VISIBLE);
        }

        getContext().getUITaskDispatcher().delayDispatch(() -> {

            int size = legends.size();
            // 图例行数
            int circulation = size / mColumn + (size % mColumn > 0 ? 1 : 0);
            LogUtil.loge("201812201056", "图例行数 = " + circulation + "->集合总数size = " + size
                    + "->size / mColumn = " + (size / mColumn) + "->size % mColumn = " + (size % mColumn));
            if (mColumn > size) {
                mColumn = size;
            }

            removeAllComponents();
            DirectionalLayout labelLayout;
            PointView pointView;
            Text labelTv;
            LayoutConfig params = new LayoutConfig(
                    LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
            for (int i = 0; i < circulation; i++) {
                labelLayout = new DirectionalLayout(mContext);
                labelLayout.setOrientation(DirectionalLayout.HORIZONTAL);
                labelLayout.setLayoutConfig(params);
                if (circulation == 1) { // 只有一行，水平居中
                    labelLayout.setAlignment(LayoutAlignment.CENTER);
                } else { // 左对齐
                    labelLayout.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.VERTICAL_CENTER);
                    if (i > 0) { // 大于一行,第一行不设置行间上间距
                        params.setMarginTop(mLegendVerMargin);
                    }
                    params.setMarginLeft(mLegendOffsetLeft);
                }
                for (int j = 0; j < mColumn; j++) { // 创建label
                    final int pos = i * mColumn + j;

                    if (pos > size - 1) { // 全取干净了
                        break;
                    }

                    pointView = new PointView(mContext);
                    pointView.setWidth(pointWH);
                    pointView.setHeight(pointWH);
                    pointView.setPointWH(pointWH);
                    pointView.setColor(new Color(colors[pos]));
                    labelLayout.addComponent(pointView);

                    labelTv = new Text(mContext);
                    labelTv.setTextAlignment(TextAlignment.VERTICAL_CENTER);
                    labelTv.setPadding(mLegendLabelAndPointMargin, 0, 0, 0);
                    labelTv.setWidth(mColumnWidth);
                    labelTv.setText(legends.get(pos));
                    labelTv.setTextColor(new Color(mLabelColor));
                    labelTv.setTextSize((int) mLabelSize);//mLabelSize
                    labelLayout.addComponent(labelTv);
                    labelTv.setClickedListener(component -> {
                        if (mListener != null) {
                            mListener.onLegendClick(pos);
                        }
                    });
                }
                addComponent(labelLayout);
            }
        }, 50);
    }

    private LegendListener mListener;

    public void setLegendListener(LegendListener listener) {
        mListener = listener;
    }

    public interface LegendListener {
        void onLegendClick(int label);
    }

}
